//
//  EmotionTextView.m
//  微博2期
//
//  Created by J on 15/12/17.
//
//

#import "EmotionTextView.h"
#import "Emotion.h"
#import "UITextView+Extension.h"
#import "EmotionAttachment.h"
@implementation EmotionTextView

- (void)insertEmotion:(Emotion *)emotion{
    if (emotion.code) {
        [self insertText:emotion.code.emoji];//insertText:从光标位置插入
    }else if(emotion.png){
//        NSMutableAttributedString * attributedText =[[NSMutableAttributedString alloc]init];
//        [attributedText appendAttributedString:self.attributedText];//拼接之前的内容(图片,文字)
        EmotionAttachment * attch = [[EmotionAttachment alloc]init];
        attch.emotion = emotion;//传递模型
//        UIImage * image= [UIImage imageNamed:emotion.png];//加载图片
//        attch.image = image;
        CGFloat attchWH = self.font.lineHeight;//设置图片尺寸
        attch.bounds = CGRectMake(0, -4, attchWH, attchWH);
        
        //根据附件创建一个属性文字
        NSAttributedString * imageStr =[NSAttributedString attributedStringWithAttachment:attch];//拼接图片字        
//        NSMutableAttributedString * abc = (NSMutableAttributedString*)self.attributedText;
////        插入属性文字到光标位置
//        [abc addAttribute:NSFontAttributeName value:self.font range:NSMakeRange(0, abc.length)];
        
        [self insertAttrbuteText:imageStr settingBlock:^(NSMutableAttributedString *attributedText) {//在赋值之前调用Block
            [attributedText addAttribute:NSFontAttributeName value:self.font range:NSMakeRange(0, attributedText.length)];
        }];//插入文字
    }
}

- (NSString *)fullText{
    NSMutableString* fullText = [NSMutableString string];//遍历所有文字包括图片文字
    [self.attributedText enumerateAttributesInRange:NSMakeRange(0, self.attributedText.length) options:0 usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
        
//        [self.attributedText attributedSubstringFromRange:range];//返回指定范围内文字
        
        //判断是否是表图片情
     EmotionAttachment * attch  = attrs[@"NSAttachment"];
        if (attch) {//图片
            [fullText appendString:attch.emotion.chs];
        }else{//普通文本
            
         NSAttributedString* str =   [self.attributedText attributedSubstringFromRange:range];
            [fullText appendString:str.string];
        }
        
        
    }];
    
    return fullText;
    
}

@end
